package com.atguigu.tingshu.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 上游服务----->下游服务
 * 只拦截OpenFeign请求，将上游服务拥有的token手动设置到请求头：token
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 每次远程调用都会执行apply方法
     * @param requestTemplate
     */
    public void apply(RequestTemplate requestTemplate){
        //  获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //异步编排 与 MQ消费者端 与 定时任务中  为 null 避免出现空指针
        if(null != requestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            //获取到当前-上游服务请求头
            String token = request.getHeader("token");
            //为真正发起远程调用requestTemplate对象设置token 将token传递到下游服务中
            requestTemplate.header("token", token);
        }
    }
}
